﻿using Learun.Util.SqlSugar;
using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-03-03 16:57
    /// 描 述：元件库目录表
    /// </summary>
    public class ec_library_catalogueService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_library_catalogueEntity> _libraryCatalogueRepository => new Repository<ec_library_catalogueEntity>();
        #endregion
        #region 获取数据

        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<ec_library_catalogueEntity> GetList(string queryJson)
        {
            try
            {
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append("SELECT t.* ,t2.F_RealName CreateUserName ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    strSql.Append(@",(SELECT GROUP_CONCAT(st1.LibraryCatalogueName SEPARATOR '/') FROM ec_library_catalogue st1 WHERE FIND_IN_SET(st1.LibraryCatalogueID,t.FullPath)) AS FullPathCN");
                    strSql.Append("  FROM ec_library_catalogue t ");
                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    var ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($@",(SELECT GROUP_CONCAT(st1.LibraryCatalogueName SEPARATOR '/') FROM ec_library_catalogue_{ProjectEntity.ProjectIndex} st1 WHERE FIND_IN_SET(st1.LibraryCatalogueID,t.FullPath)) AS FullPathCN");
                    strSql.Append($"  FROM ec_library_catalogue_{ProjectEntity.ProjectIndex} t ");
                }
                strSql.Append(@" LEFT JOIN lr_base_user t2 ON t.CreateUserID = t2.F_UserId ");
                strSql.Append("  WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["LibraryCatalogueName"].IsEmpty())
                {
                    dp.Add(new SugarParameter("LibraryCatalogueName", "%" + queryParam["LibraryCatalogueName"].ToString() + "%", DbType.String));
                    strSql.Append(" AND t.LibraryCatalogueName Like @LibraryCatalogueName ");
                }
                if (!queryParam["CurLibraryCatalogueID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("CurLibraryCatalogueID", queryParam["CurLibraryCatalogueID"].ToString(), DbType.String));
                    strSql.Append(" AND LOCATE(@CurLibraryCatalogueID, FullPath) = 0 ");
                }
                strSql.Append(" ORDER BY t.OrderID ");
                //return this.BaseRepository().FindList<ec_library_catalogueEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<ec_library_catalogueEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_library_catalogueEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    return _libraryCatalogueRepository.GetById(keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@"SELECT * FROM ec_library_catalogue_{ ProjectEntity.ProjectIndex} WHERE LibraryCatalogueID = @LibraryCatalogueID ");
                    //List<ec_library_catalogueEntity> list = this.BaseRepository().FindList<ec_library_catalogueEntity>(strSql.ToString(), new { LibraryCatalogueID = keyValue }).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_library_catalogueEntity>(strSql.ToString(), new { LibraryCatalogueID = keyValue });
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    //元件库目录删除时，删除子目录和目录下的元件库文件记录。
                    SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_library_file WHERE LibraryCatalogueID IN (SELECT DISTINCT ST1.LibraryCatalogueID FROM ec_library_catalogue ST1 WHERE FIND_IN_SET('{keyValue}',ST1.FullPath)); ");
                    _libraryCatalogueRepository.Delete(t => t.FullPath.Contains(keyValue));
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    //元件库目录删除时，删除子目录和目录下的元件库文件记录。
                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_library_file_{ ProjectEntity.ProjectIndex} WHERE LibraryCatalogueID IN (SELECT DISTINCT ST1.LibraryCatalogueID FROM ec_library_catalogue_{ ProjectEntity.ProjectIndex} ST1 WHERE FIND_IN_SET('{keyValue}',ST1.FullPath));
                                        DELETE FROM ec_library_catalogue_{ ProjectEntity.ProjectIndex} WHERE FullPath LIKE '%{keyValue}%'; ");
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_library_catalogueEntity entity, string ProjectId)
        {
            try
            {
                string fullPath = "";
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    GetFullPath(ref fullPath, entity.UpLibraryCatalogueID, entity.LibraryCatalogueID, ProjectId);
                    entity.FullPath = fullPath;
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _libraryCatalogueRepository.Update(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_library_catalogue_{ ProjectEntity.ProjectIndex}", "LibraryCatalogueID");
                        _libraryCatalogueRepository.AsUpdateable(entity).AS($"ec_library_catalogue_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
                else
                {
                    entity.Create();
                    GetFullPath(ref fullPath, entity.UpLibraryCatalogueID, entity.LibraryCatalogueID, ProjectId);
                    entity.FullPath = fullPath;
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _libraryCatalogueRepository.Insert(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_library_catalogue_{ ProjectEntity.ProjectIndex}");
                        _libraryCatalogueRepository.AsInsertable(entity).AS($"ec_library_catalogue_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 完整路径保存父级和子级的分类ID，用逗号分割
        /// </summary>
        /// <returns></returns>
        public void GetFullPath(ref string fullPath, string parentId, string id, string ProjectId)
        {
            if (string.IsNullOrEmpty(parentId) || parentId == "0")
            {
                fullPath = id;
            }
            else
            {
                var entity = GetEntity(parentId, ProjectId);
                fullPath = entity?.FullPath + "," + id;
            }
        }
        #endregion

    }
}
